package com.yy.jhl.ui.manager.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yy.common.base.BaseActivity;
import com.yy.common.commonutils.StringUtil;
import com.yy.common.commonutils.TimeUtil;
import com.yy.common.commonwidget.OnNoDoubleClickListener;
import com.yy.jhl.R;
import com.yy.jhl.bean.ProductInfo;
import com.yy.jhl.bean.SealBoxListInfo;
import com.yy.jhl.interfaces.CommonCallBack;
import com.yy.jhl.interfaces.EnsureCallBack;
import com.yy.jhl.interfaces.ProductCallBack;
import com.yy.jhl.interfaces.ProductListCallBack;
import com.yy.jhl.ui.manager.contract.SealBoxAddContract;
import com.yy.jhl.ui.manager.presenter.SealBoxAddPresenter;
import com.yy.jhl.util.DataRequestUtil;
import com.yy.jhl.util.DialogUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by libingn on 2017/12/11.
 */

public class SealBoxAddActivity extends BaseActivity<SealBoxAddPresenter> implements SealBoxAddContract.View {
    @BindView(R.id.box_code_text)
    TextView boxCodeText;
    @BindView(R.id.box_code_parent)
    LinearLayout boxCodeParent;
    @BindView(R.id.product_name_text)
    TextView productNameText;
    @BindView(R.id.product_name_parent)
    LinearLayout productNameParent;
    @BindView(R.id.product_model_text)
    TextView productModelText;
    @BindView(R.id.product_model_parent)
    LinearLayout productModelParent;
    @BindView(R.id.product_quantity_edit)
    EditText productQuantityEdit;
    @BindView(R.id.product_quantity_parent)
    LinearLayout productQuantityParent;
    @BindView(R.id.product_unit_text)
    TextView productUnitText;
    @BindView(R.id.product_unit_parent)
    LinearLayout productUnitParent;
    @BindView(R.id.product_price_text)
    TextView productPriceText;
    @BindView(R.id.product_price_parent)
    LinearLayout productPriceParent;
    @BindView(R.id.product_all_price_text)
    TextView productAllPriceText;
    @BindView(R.id.product_all_price_parent)
    LinearLayout productAllPriceParent;
    @BindView(R.id.box_time_text)
    TextView boxTimeText;
    @BindView(R.id.box_time_parent)
    LinearLayout boxTimeParent;
    @BindView(R.id.save_btn)
    Button saveBtn;
    @BindView(R.id.continue_btn)
    Button continueBtn;
    String packageId = "";
    String batchId = "";
    String packageNum = "";
    ProductInfo selectedProductInfo;
    boolean isContinueAdd = false;
    public static void startAction(Context mContext, String packageId, String batchId,String packageNum, ProductInfo item,int requestCode) {
        Intent intent = new Intent(mContext, SealBoxAddActivity.class);
        intent.putExtra("packageId", packageId);
        intent.putExtra("packageNum", packageNum);
        intent.putExtra("batchId", batchId);
        intent.putExtra("item", item);
        ((Activity)mContext).startActivityForResult(intent,requestCode);
    }
    public static void startAction(Context mContext, String packageId, String batchId,String packageNum, ProductInfo item) {
        Intent intent = new Intent(mContext, SealBoxAddActivity.class);
        intent.putExtra("packageId", packageId);
        intent.putExtra("packageNum", packageNum);
        intent.putExtra("batchId", batchId);
        intent.putExtra("item", item);
        mContext.startActivity(intent);
    }
    @Override
    public int getLayoutId() {
        return R.layout.act_seal_box_add;
    }

    @Override
    public void initView() {
        packageNum = getIntent().getStringExtra("packageNum");
        packageId = getIntent().getStringExtra("packageId");
        batchId = getIntent().getStringExtra("batchId");
        String title = "";
        if (StringUtil.isEmpty(packageId) ){
            title = "新增封箱信息";
            boxCodeParent.setVisibility(View.GONE);
        }else {
            title = "修改封箱信息";
            boxCodeParent.setVisibility(View.VISIBLE);
            boxCodeText.setText(packageNum);
            selectedProductInfo = (ProductInfo)getIntent().getSerializableExtra("item");
            fillView();
        }
        showTitle(title, new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });
        boxTimeText.setText(TimeUtil.formatData(TimeUtil.dateFormatYMD,System.currentTimeMillis()));
        productQuantityEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (selectedProductInfo != null){
                    String content = editable.toString();
                    if (StringUtil.isEmpty(content))return;
                    if (Double.parseDouble(content) >Double.parseDouble(selectedProductInfo.getQuantity())){
                        productQuantityEdit.setText("");
                        productAllPriceText.setText("");
                        showShortToast("输入数量不能超过总数量");
                    }else {
                        String allPrice = "";
                        try {
                            allPrice = StringUtil.getSingleDouble(Double.parseDouble(content)*Double.parseDouble(selectedProductInfo.getUnit_price()));
                        }catch (Exception e){
                            allPrice = "0.0" ;
                        }
                        productAllPriceText.setText(allPrice);
                    }
                }

            }
        });
    }
    @OnClick({R.id.product_name_parent,R.id.save_btn, R.id.continue_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.product_name_parent:
                    DataRequestUtil.getInstance(mContext).getProductList(batchId,packageId, new ProductListCallBack() {
                        @Override
                        public void getCallBack(List<ProductInfo> retList) {
                            List<ProductInfo> productInfos = new ArrayList<ProductInfo>();
                            if (retList != null && retList.size() > 0){
                                int size = retList.size();
                                for (int i =0;i<size;i++){
                                    if (!StringUtil.isEmpty(retList.get(i).getQuantity()) && !"0".equals(retList.get(i).getQuantity())){
                                        productInfos.add(retList.get(i));
                                    }
                                }
                            }
                            if (productInfos.size() == 0){
                                showShortToast("暂无可用的产品列表信息");
                                return;
                            }
                            DialogUtil.showSelectDialogView(mContext, productInfos, new ProductCallBack() {
                                @Override
                                public void getCallBack(ProductInfo productInfo) {
                                    selectedProductInfo = productInfo;
                                    fillView();
                                }
                            });
                        }
                    });
                break;
            case R.id.save_btn:
                isContinueAdd = false;
                submitData();
                break;
            case R.id.continue_btn:
                isContinueAdd = true;
                submitData();
                break;
        }
    }

    /**
     * 提交数据
     */
    private void submitData(){
        if (selectedProductInfo == null){
            showShortToast("请先选择相应产品");
            return;
        }
        int packageSum = 0 ;
        try {
            packageSum = Integer.parseInt(productQuantityEdit.getText().toString().trim());
        }catch (Exception e){

        }
        if (packageSum <= 0){
            showShortToast("产品数量不能为空");
            return;
        }
        JSONObject productObject = new JSONObject();
        JSONArray productArray = new JSONArray();
        try {
            productObject.put("batch_order_item_id",selectedProductInfo.getBatch_order_item_id());
            productObject.put("quantity",packageSum);
            productObject.put("package_id",packageId);
//            productObject.put("id",selectedProductInfo.getId());
            productArray.put(productObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mPresenter.modifyPackage(packageId,batchId,packageNum,productArray.toString());
    }
    /**
     * 填充数据
     */
    protected void fillView(){
        productNameText.setText(selectedProductInfo.getItem_name());
        productModelText.setText(selectedProductInfo.getModel());
        productUnitText.setText(selectedProductInfo.getUnit());
        productPriceText.setText(selectedProductInfo.getUnit_price());
        productQuantityEdit.setText(selectedProductInfo.getQuantity());
        String allPrice = "";
        try {
            allPrice = StringUtil.getSingleDouble(Double.parseDouble(selectedProductInfo.getQuantity())*Double.parseDouble(selectedProductInfo.getUnit_price()));
        }catch (Exception e){
            allPrice = "0.0" ;
        }
        productAllPriceText.setText(allPrice);
    }

    @Override
    public void modifyPackageSuccess(String package_id,final String pack_num,String is_finish) {
        packageId = package_id;
        packageNum = pack_num;
        //0:no 1:yes
        if ("0".equals(is_finish)){
            if (isContinueAdd){
                //初始化界面
                boxCodeParent.setVisibility(View.VISIBLE);
                boxCodeText.setText(pack_num);
                selectedProductInfo = null;
                productNameText.setText("点击选择");
                productModelText.setText("");
                productUnitText.setText("");
                productPriceText.setText("");
                productAllPriceText.setText("");
                productQuantityEdit.setText("");
            }else {
                Intent intent = new Intent();
                intent.putExtra("is_finish","0");
                setResult(RESULT_OK,intent);
                finish();
            }
        }else {
            Intent intent = new Intent();
            intent.putExtra("is_finish","1");
            setResult(RESULT_OK,intent);
            finish();
        }


    }

    @Override
    public void modifyPackageFail() {

    }
}
